﻿/*************************************************
事件派发器
author：Daixiwei
**************************************************/
using System;
using System.Collections;

namespace taurus.client
{
    /// <summary>
    /// 事件监听委托
    /// </summary>
    /// <param name="evt">事件源</param>
    public delegate void IEventListener(Event evt);

    /// <summary>
    /// EventDispatcher 事件派发器类，负责进行事件的发送和侦听。
    /// </summary>
    public class EventDispatcher
    {
        /// <summary>
        /// 
        /// </summary>
        private Hashtable _listeners = new Hashtable();

        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="listener"></param>
        public void addEventListener(string eventName, IEventListener listener)
        {
            IEventListener a = _listeners[eventName] as IEventListener;
            a = (IEventListener)Delegate.Combine(a, listener);
            _listeners[eventName] = a;
        }

        /// <summary>
        /// 派发消息
        /// </summary>
        /// <param name="evt"></param>
        public void dispatchEvent(Event evt)
        {
            IEventListener delegate2 = _listeners[evt.getName()] as IEventListener;
            if (delegate2 != null)
            {
                try
                {
                    delegate2(evt);
                }
                catch (Exception exception)
                {
                    throw new Exception(" Error dispatching event " + evt.getName(), exception);
                }
            }
        }

        /// <summary>
        /// 移除所有事件
        /// </summary>
        public void removeAllEventListener()
        {
            this._listeners.Clear();
        }

        /// <summary>
        /// 移除指定事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="listener"></param>
        public void removeEventListener(string eventName, IEventListener listener)
        {
            IEventListener source = this._listeners[eventName] as IEventListener;
            if (source != null)
            {
                source = (IEventListener)Delegate.Remove(source, listener);
            }
            _listeners[eventName] = source;
        }
    }
}

